# Copyright (c) 2023 az13js
# 基金分类/classify-funds is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of
# the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#          http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF
# ANY KIND,EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
# NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.

from km import AlgorithmLogic
import csv
import os
import re
import shutil

def readData(csvFileName):
    totalColumnNumber = None
    with open(csvFileName, 'r') as fp:
        reader = csv.reader(fp)
        for row in reader:
            if totalColumnNumber is None:
                totalColumnNumber = len(row) - 3
            data = []
            for i in range(totalColumnNumber):
                data.append((float(row[i + 2]) / float(row[i + 1]) - 1.0) * 100.0)
            yield (data, row[0])

if __name__ == '__main__':
    # 删除旧的文件。
    fileNeedDelete = []
    pattern = re.compile(r"fund_sort_average_nav_c[0-9]+_s[0-9]+\.csv")
    for entry in os.scandir('reports'):
        if entry.is_file() and re.match(pattern, entry.name):
            fileNeedDelete.append(entry.name)
    for fileName in fileNeedDelete:
        os.remove('reports' + os.sep + fileName)

    fileName = 'reports' + os.sep + 'fund_sort_average_nav.csv'

    logic = AlgorithmLogic()
    for record in readData(fileName):
        logic.addSampleData(record[0])

    silhouetteCoefficients = []
    silhouetteCoefficientsFiles = []
    categorys = []
    for i in range(40):
        logic.run(10, 100, 1E-6)
        silhouetteCoefficients.append(logic.getSilhouetteCoefficient())
        center = []
        for c in logic.getCategorys():
            center.append(c.getCenter().getData())
        categorys.append(center)

        datasCategory = logic.getSampleCategory()
        with open(fileName, 'r') as fp:
            writeFileName = 'reports' + os.sep + 'fund_sort_average_nav_c' + str(i) + '_s' + str(int(silhouetteCoefficients[i] * 100)) + '.csv'
            with open(writeFileName, 'w', newline = '') as wfp:
                reader = csv.reader(fp)
                writer = csv.writer(wfp)
                line = 0
                for row in reader:
                    line = line + 1
                    newRow = row + [datasCategory[line - 1]]
                    writer.writerow(newRow)
            print('Silhouette coefficient: %f, at %d, file: %s'%(silhouetteCoefficients[i], i, writeFileName))
            silhouetteCoefficientsFiles.append(writeFileName)

    maxSilhouetteCoefficientsIndex = silhouetteCoefficients.index(max(silhouetteCoefficients))
    finallyFileName = silhouetteCoefficientsFiles[maxSilhouetteCoefficientsIndex]
    print('The maximum value is at %d, =%f, file: %s'%(maxSilhouetteCoefficientsIndex, silhouetteCoefficients[maxSilhouetteCoefficientsIndex], finallyFileName))
    shutil.copyfile(finallyFileName, 'reports' + os.sep + 'finally_report.csv')
